# -*- coding: utf-8 -*-
import redis
import urllib


class redisClient(object):
    # pool = redis.ConnectionPool(host='phonics.brightdot.cn',
    #                             port='35557',
    #                             password='@wecredo2016',
    #                             db='2')

    pool = redis.ConnectionPool(host='127.0.0.1',
                                port='6379',
                                password='',
                                db='2')
    r = redis.Redis(connection_pool=pool)

    def rmrIp(self, val):
        redisClient.r.srem('effectiveip', val)

    # 获取可用代理ip
    def getEffectiveIp(self):
        exits = redisClient.r.spop('effectiveip')
        if exits != None:
            return exits.decode()
        else:
            # 请求接口获取新的ip列表，存至redis
            # api链接
            api_url = "http://tpv.daxiangdaili.com/ip/?tid=559856631618265&num=100&category=2&protocol=https&filter=on"
            req = urllib.request.urlopen(api_url)
            print(req.code)  # 获取Reponse的返回码
            responseIps = req.read().decode('utf-8')  # 获取API返回内容
            if responseIps is not None:
                responseIps = responseIps.split('\r\n')
                for i in responseIps:
                    redisClient.r.sadd('effectiveip', i)
            return redisClient.getEffectiveIp(self)
        return exits.decode() if (exits is not None) else None


    # 请求失败的结果，保存下来，最后处理
    def saveFaild(self, url):
        redisClient.r.sadd('Lactationer:slave:failed', url)

    @property
    def getEffectiveUrl(self):
        exits = redisClient.r.spop('Lactationer:exists')
        return exits.decode() if (exits is not None) else None
